import log4js from "log4js";

class Logger {
  constructor(path) {
    this.path = path;
    this.logger = null;
    this.init();
  }

  init() {
    this.configure();
    this.getLogger();
  }

  configure() {
    log4js.configure({
      appenders: {
        out: {
          type: "stdout", // 输出到控制台
          layout: { type: "colored" }, // 彩色输出
        },
        file: {
          type: "file", // 输出到文件
          filename: this.path, // 指定日志文件路径和名称
        },
      },
      categories: {
        default: {
          appenders: ["out", "file"], // 使用 out 和 file 输出器
          level: "debug", // 设置日志级别为 debug
        },
      },
    });
  }

  getLogger() {
    this.logger = log4js.getLogger("default");
  }

  // 返回中间件函数
  middleware() {
    return (req, res, next) => {
      this.logger.debug(`${req.method} ${req.url}`);
      next();
    };
  }
}

export default Logger;
